﻿#include "Time.h"

namespace DYEngine
{
	long Time::mGameTime = 0;
	unsigned int Time::mFrameRate = 0;
	long Time::mFramePeriod = 0;
	float Time::mDeltaTime = 0;
	float Time::mScale = 0;
	float Time::mStartTime = 0;

	// 获取真实时间
	float Time::GetRealTime()
	{
		return (float)(clock() / 1000.0);
	}

	// 获取时钟，单位毫秒
	long Time::GetClock()
	{
		return clock();
	}

	// 获取游戏时间
	float Time::GetGameTime()
	{
		return mGameTime;
	}

	/// <summary>
	/// 设置上一帧的耗时
	/// </summary>
	/// <param name="pDeltaTime"></param>
	void Time::SetDeltaTime(long pDeltaTime)
	{
		mDeltaTime = pDeltaTime / 1000.0f;
	}

	/// <summary>
	/// 获取上一帧的耗时
	/// </summary>
	/// <returns></returns>
	float Time::GetDeltaTime()
	{
		return mDeltaTime;
	}

	/// <summary>
	/// 设置帧率
	/// </summary>
	/// <param name="pFrameRate"></param>
	void Time::SetFrameRate(unsigned int pFrameRate)
	{
		mFrameRate = pFrameRate;
		mFramePeriod = 1000L / mFrameRate;
	}

	/// <summary>
	/// 获取帧率
	/// </summary>
	/// <returns></returns>
	unsigned int Time::GetFrameRate()
	{
		return mFramePeriod;
	}

	long Time::GetFramePeriod()
	{
		return mFramePeriod;
	}

	void Time::SetTimeScale(float pTimeScale)
	{
		mScale = pTimeScale;
	}

	float Time::GetTimeScale()
	{
		return mScale;
	}

	void Time::Update()
	{
		long endTime = Time::GetClock();
		long useTime = endTime - mStartTime;

		long sleepTime = 0;
		long deltaTime = 0;
		long framePeriod = Time::GetFramePeriod();
		if (useTime <= framePeriod)
		{
			deltaTime = framePeriod;
		}
		else
		{
			deltaTime = (useTime / framePeriod + 1) * framePeriod;
		}

		// 处理断点情况
		if (deltaTime > 1000L)
		{
			deltaTime = framePeriod;
		}

		sleepTime = deltaTime - useTime;
		Time::SetDeltaTime(deltaTime);

		if (sleepTime > 0)
		{
			Sleep(sleepTime);
			endTime = clock();
		}

		mStartTime = endTime;
	}
}
